package server

import (
	"npxy-go/pkg/tcp"
	"sync"
)

type portalServerManager struct {
	mu      *sync.Mutex
	servers map[serverKey]*tcp.Server
}

type serverKey struct {
	localPort uint16
	proxyPort uint16
}

func newPortalServerManager() *portalServerManager {
	return &portalServerManager{mu: new(sync.Mutex), servers: make(map[serverKey]*tcp.Server)}
}

func (p portalServerManager) add(key serverKey, srv *tcp.Server) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.servers[key] = srv
}

func (p portalServerManager) close(key serverKey) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if srv, ok := p.servers[key]; ok {
		srv.Close()
	}
	delete(p.servers, key)
}

func (p portalServerManager) closeAll() {
	p.mu.Lock()
	defer p.mu.Unlock()
	for _, srv := range p.servers {
		srv.Close()
	}
	p.servers = make(map[serverKey]*tcp.Server, 0)
}
